import React, { Component } from 'react';
import { Card } from 'antd';
import echarts from 'echarts/lib/echarts'
import ReactEcharts from 'echarts-for-react';
import { formatterUnitOfData } from '@/utils/utils'
import styles from '../index.less'

import 'echarts/map/js/china';
//引入地图和柱状图
import 'echarts/lib/chart/map';
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';

const originName = '洛阳';


//实际数据处理思路：

//地理坐标位置
const testFlyGeo = [
  { name: '洛阳', lng: 112.460299, lat: 34.62677 },
  { name: '西安', lng: 108.946466, lat: 34.347269 },
  { name: '兰州', lng: 103.84044, lat: 36.067321 },
  { name: '乌鲁木齐', lng: 87.62444, lat: 43.830763 },
  { name: '包头', lng: 109.846544, lat: 40.662929 },
  { name: '昆明', lng: 104.846544, lat: 38.662929 },
]

//飞线数据

const testFlyVal = [
  { from: '西安', to: '洛阳', value: { '套数': 10, '面积': 10 } },
  { from: '兰州', to: '洛阳', value: { '套数': 10, '面积': 10 } },
  { from: '乌鲁木齐', to: '洛阳', value: { '套数': 10, '面积': 10 } },
  { from: '包头', to: '洛阳', value: { '套数': 10, '面积': 10 } },
]



//地理位置经纬度信息处理
const arrFlyGeo = (data) => {
  const newFlyGeo = {}
  data.map((item) => {
    const { name, lng, lat } = item
    newFlyGeo[name] = [lng, lat]
  })
  return newFlyGeo
}

//数据转换，转换后格式：[{fromName:'cityName', toName:'cityName', coords:[[lng, lat], [lng, lat]]}, {...}]
const convertFlyData = function (data, flyGeo, staticts) {//飞线数据处理
  let res = [];
  const flyGeos = arrFlyGeo(flyGeo)
  for (let i = 0; i < data.length; i++) {
    let dataItem = data[i];
    let toCoord = flyGeos[dataItem.to];
    let fromCoord = flyGeos[dataItem.from];
    let coordValue = dataItem.value
    if (fromCoord && toCoord) {
      res.push({
        fromName: dataItem.from,
        toName: dataItem.to,
        coords: [fromCoord, toCoord],
        value: coordValue[staticts],
        staticts: staticts
      });
    }
  }
  return res;
};


class MigrationMap extends Component {

  constructor() {
    super()
    this.state = ({
      flySeries: [],
      staticts: '面积',
      minNumber: 0,
      maxNumber: 0,
      mapData: []
    })
  }

  componentWillReceiveProps(nextprops) {
    const that = this
    //数据处理

    const handSymbolSIze = (val, max, min, isSmall = false, params) => {
      const { dataIndex } = params
      const scatterSizes = [26, 24, 22, 20, 18]
      const computedScale = (parseFloat(val) - min) / (max - min) * 1800
      const scale = computedScale > 25 ? isSmall ? 16 : scatterSizes[dataIndex] : computedScale
      return scale
    }
    //处理迁徙图数据
    const originMap = nextprops.data || []
    // const {dataType} = nextprops
    const statictsMap = { '面积': 'new_square', '套数': 'new_number' }
    const maxNumber = Math.max.apply(Math, originMap.map(item => { return item[statictsMap[nextprops.staticts]] }))
    const minNumber = Math.min.apply(Math, originMap.map(item => { return item[statictsMap[nextprops.staticts]] }))
    let flyGeo = []
    let flyVal = []
    let originplace = ''
    if (originMap && originMap.length) {
      originplace = originMap[0].region_name
      const toCenter = originMap[0].region_center.split(',')
      flyGeo.push({ name: originplace, lng: parseFloat(toCenter[0]), lat: parseFloat(toCenter[1]) })

      originMap.map((item) => {
        const { born_province, born_province_center, new_number, new_square } = item
        let lnglat = born_province_center.split(',')//拆分经纬度信息

        let obj = {}
        obj.name = born_province
        obj.lng = parseFloat(lnglat[0])
        obj.lat = parseFloat(lnglat[1])
        flyGeo.push(obj)
        flyVal.push({ from: born_province, to: originplace, value: { '套数': new_number, '面积': new_square } })
      })
      // flyVal.push({ from: originplace, to: originplace, value: { '套数': 0, '面积': 0 } })
    }

    //报表配置
    let flySeries = []
    let forObj = []
    forObj.push(['德宏州', flyVal])
    forObj.forEach(function (item, i) {
      flySeries.push(
        { //飞线配置
          name: item[0],
          type: 'lines',
          zlevel: 1,
          symbol: ['none', 'none'],
          symbolSize: 0,
          effect: { //特效线配置
            show: true,
            period: 5, //特效动画时间，单位s
            trailLength: 0.6, //特效尾迹的长度，从0到1
            symbol: 'arrow',
            symbolSize: 2,
            color: '#ffff00'
          },
          lineStyle: {
            color: '#ffff00',
            width: 0,
            opacity: 0.1,
            curveness: 0.2 //线的平滑度
          },
          data: convertFlyData(item[1], flyGeo, nextprops.staticts)
        },
        {    //点配置
          name: item[0],
          type: 'effectScatter',
          coordinateSystem: 'geo',
          zlevel: 2,
          symbolSize: (val, params) => handSymbolSIze(val[2], maxNumber, minNumber, false, params),
          itemStyle: {
            color: '#ffff00'
          },
          rippleEffect: { //涟漪特效
            color: '#ffff00',
            period: 5, //特效动画时长
            scale: 2, //波纹的最大缩放比例
            brushType: 'stroke' //波纹的绘制方式：stroke | fill
          },
          // label: {
          //   normal: {
          //     color: '#1890ff',
          //     show: false,
          //     position: 'right',
          //     formatter: '{b}'
          //   }
          // },
          data: item[1].sort((a, b) => b.value[nextprops.staticts] - a.value[nextprops.staticts])
            .slice(0, 5)
            .map(function (dataItem) {//item[1]是飞线数据
              const flyGeos = arrFlyGeo(flyGeo)
              return {
                name: dataItem.from,
                value: flyGeos[dataItem.from].concat([dataItem.value[nextprops.staticts]], [nextprops.staticts])//合并后形式["lng", "lat", "value"] [109.846544, 40.662929, 350]
              };
            })
        },
        { //与上层的点叠加
          name: item[0],
          type: 'scatter',
          coordinateSystem: 'geo',
          zlevel: 3,
          symbol: 'circle',
          // symbol: 'image://',
          itemStyle: {
            color: '#ffff00'
          },
          showAllSymbol: true,
          symbolSize: (val, params) => handSymbolSIze(val[2], maxNumber, minNumber, true, params),
          data: item[1].map(function (dataItem) {
            const flyGeos = arrFlyGeo(flyGeo)
            return {
              name: dataItem.from,
              value: flyGeos[dataItem.from].concat([dataItem.value[nextprops.staticts]], [nextprops.staticts])
            };
          })
        });
    });
    // const mapData = this.toHotMap(flySeries)
    this.toHotMap(flySeries)

    this.setState({
      flySeries,
      staticts: nextprops.staticts,
      // minNumber: (minNumber == Infinity || flySeries[0].data.length<3? 0 : minNumber),
      minNumber: 0,
    })
  }

  //地图热力数据获取   热力区别最佳效果max=mid*3
  toHotMap = (series) => {
    const arr = [...series]
    let mapData = []
    let numArr = []
    arr[0].data.map(item => {
      let obj = {}
      obj.name = item.fromName
      obj.value = item.value
      // if (item.fromName!='云南') {
      //   mapData.push(obj)
      // }
      mapData.push(obj)
      numArr.push(item.value)
    })
    numArr.sort(function (a, b) { return a - b })
    const mid = numArr[(numArr.length / 2).toFixed() - 1]
    const max = numArr.length > 2 ? mid * 3 : mid
    this.setState({
      mapData,
      maxNumber: max ? max : 0
    })
  }

  getOption = () => {
    let option = {
      backgroundColor: '#000716',
      title: {
        text: '',
        subtext: '',
        left: 'center',
        textStyle: {
          color: '#fff'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: item => {
          // if (params.seriesType == "effectScatter") {
          //   return "线路：" + params.data.name + "" + params.data.value[2];
          // } else if (params.seriesType == "lines") {
          //   // return params.data.fromName + "至" + params.data.toName + "<br />" + params.data.value;
          //   return (params.data.staticts == '套数' ? '人群来源地:' + params.data.fromName + '<br />' + params.data.value + '(套)' : '人群来源地:' + params.data.fromName + '<br />' + params.data.value + '(平方米)')
          // } else {
          //   return params.data.value[3] == '套数' ? '人群来源地:' + params.name + '<br />' + params.data.value[2] + '(套)' : '人群来源地:' + params.name + '<br />' + params.data.value[2] + '(平方米)'
          // }
          let amount = item.value, fromName = ''
          if (item.seriesType === 'map') {
            fromName = item.name
          } else if (item.seriesType === 'lines') {
            fromName = item.data.fromName
          } else {
            amount = item.value[2]
            fromName = item.name
          }

          const { value, unit } = formatterUnitOfData(this.state.staticts, amount)
          const template = `
          <div class=${styles.tooltip}>
            <p>${'人群来源地:' + fromName}</p>
            <div class=${styles.content}>
                <span class=${styles.circle} style="background: ${item.color}"></span>
                ${this.state.staticts}:
                <span class=${styles.amount}>
                  ${value + unit}
                </span>
            </div>
          </div>
          `
          return template
        }
      },
      geo: {
        map: 'china',
        aspectScale: 0.85,
        layoutCenter: ["50%", "50%"], //地图位置
        layoutSize: '140%',
        label: {
          show: false
        },
        itemStyle: {
          normal: {
            shadowColor: '#276fce',
            shadowOffsetX: 0,
            shadowOffsetY: 15,
            opacity: 0.5,
          },
          emphasis: {
            color: '#ccc',
            areaColor: '#0c274b',
            borderColor: '#ddd',
            borderWidth: 1.5,
            opacity: 0.8,
          }
        },
        roam: false,
        regions: [
          {
            name: "南海诸岛",
            itemStyle: {
              normal: {
                opacity: 0, // 为 0 时不绘制该图形
              }
            },
            label: {
              show: false // 隐藏文字
            }
          }
        ],
        top: '-6%',
        bottom: '5%',
        left: '13%',
        right: '13%'
      },
      visualMap: {
        // type:'piecewise',
        min: this.state.minNumber,
        max: this.state.maxNumber,
        text: ['High', 'Low'],
        realtime: false,
        calculable: false,
        show: (this.state.mapData.length > 0),
        inRange: {
          // color: ['#091f3c', '#1bd4e1']
          color: ['#9dcbe8', '#0354f6']
        }
      },
      series: [
        // 常规地图
        {
          type: 'map', // 系列类型
          name: 'map', // 系列名称
          geoIndex: 1,
          mapType: 'china',
          aspectScale: 0.85,
          layoutCenter: ["50%", "50%"], //地图位置
          layoutSize: '140%',
          zoom: 1, //当前视角的缩放比例
          // roam: true, //是否开启平游或缩放
          scaleLimit: { //滚轮缩放的极限控制
            min: 1,
            max: 2
          },
          label: {
            normal: { //静态的时候展示样式
              show: true, //是否显示地图省份得名称
              color: '#fff',
              fontSize: 12,
              // fontWeight: 'bold',
            },
            emphasis: { //动态展示的样式
              color: '#43d0d6',
            },
          },
          itemStyle: {
            normal: {
              areaColor: '#091f3c',
              borderColor: '#3971a9',
              borderWidth: 1,
              opacity: 0.8,
            },
            emphasis: {
              color: '#ccc',
              areaColor: '#0c274b',
              borderColor: '#3971a9',
              borderWidth: 1.5,
              opacity: 0.8,
            }
          },
          data: this.state.mapData || []
        },
        ...this.state.flySeries
      ]
      // series: series
    };
    return option
  }

  render() {
    return (
      <ReactEcharts option={this.getOption()} theme="Imooc"
        style={{ height: '100%' }} />
    )
  }
}
export default MigrationMap
